<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\ResponseException;
use App\Models\Goods;
use App\Models\GoodsSku;
use App\Models\SeckillGoods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class SecKillController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $goodsList = SeckillGoods::query()
                    ->select('*')
                    ->orderBy('id','desc')
                    ->paginate(10);

        return view('admin.sec_kill.index',compact('goodsList'));
    }

    /**
     * ajax改变秒杀商品状态
     * User: Clannad ~ ☆
     * Date: 2020/3/10 0010 17:22
     * @param Request $request
     * @throws ResponseException
     */
    public function ajaxChangeStatus(Request $request)
    {
        $id =  $request->input('id');

        $seckill = SeckillGoods::find($id);

        if(!$seckill){
            throw new ResponseException(404,'秒杀商品不存在');
        }

        if(strtotime($seckill['start_time']) < time() && strtotime($seckill['end_time']) > time()){
            throw new ResponseException(400,'活动已经开始，不能关停');
        }

        $status = 0;

        if($seckill->kill_status == 1) {
            $seckill->kill_status = 0;
            $status = 0;
        }
//        }else if($seckill->kill_status == 0){
//            $seckill->kill_status = 1;
//            $status = 1;
//        }

        $seckill->save();

        throw new ResponseException(200,'ok',['status'=>$status]);
    }

    /**
     * 删除秒杀商品
     * User: Clannad ~ ☆
     * Date: 2020/3/10 0010 17:38
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Request $request)
    {
        $id = $request->input('id');
        $seckill = SeckillGoods::findOrfail($id);




        //取出每一个组合的规格sku，对它们进行入队
        $goods_sku = GoodsSku::query()
            ->select('sku_list', 'goods_id', 'inventory')
            ->where('goods_id', $seckill['goods_id'])
            ->get()->toArray();

        foreach ($goods_sku as $k => $v) {
            //先删除redis的数据
            $key = 'seckill_goods_stock:goods_id:' . $seckill['goods_id'] . ':sku:' . $v['sku_list'];
            for ($i = 0; $i < $v['inventory']; $i++) {
                Redis::ltrim($key,1,0);
            }
        }
        //改变商品表状态
        $goods = Goods::findOrfail($seckill->goods_id);
        $goods->kill_status = 0;
        $goods->save();

        $seckill->delete();

        return back()->with('info','删除成功');
    }
}
